<template>
  <div class="container" :class="{'darkmode' : isDarkmode}">
    <div id="top" class="top">
      <div class="top-left">
        <div class="top-left-logo" @click="clickLogo()">
          <img src="../assets/images/logo.png" alt="Logo">
        </div>
        <!-- 搜索开始 -->
        <div class="top-left-search">
          <div class="top-left-search-input">
            <!-- 可以通过value-key属性控制匹配的字段 -->
            <el-autocomplete
              popper-class="my-autocomplete"
              v-model="searchQuery"
              :fetch-suggestions="querySearch"
              placeholder="请输入你需要搜索的内容"
              clearable
              @select="handleSelect"
            >
              <template #default="{ item }">
                <span v-html="item.value"></span>
              </template>
            </el-autocomplete>
          </div>
          <!-- 点击事件放在div点击哪里都可以跳转 -->
          <div class="top-left-search-icon" @click="clickSearchEvent">
            <el-icon style="height: 100%; width: 100%"><Search /></el-icon>
          </div>
        </div>
        <!-- 搜索结束 -->
      </div>
      <div class="top-right">
        <div class="top-right-person" @click="clickPersonalCenterEvent">
          <img :src="avatar" alt="头像">
          <span class="nickname">{{ nickname }}</span>
        </div>
      </div>
    </div>
    <div class="centre">
      <!-- 左侧图标开始 -->
      <div class="centre-left">
        <div class="centre-left-interaction">
          <div @click="handleUpvoteClick" :class="isUpvoteActivate ? 'centre-left-interaction-upvoteKnot-activate' : 'centre-left-interaction-upvoteKnot-default'">
            <div class="centre-left-interaction-upvote">
              <el-icon :size="30" class="iconfont icon-dianzan"></el-icon>
            </div>
            <div class="likeNum">{{article.likeNum}}</div>
          </div>
          <!-- 目前收藏和评论数先用喜欢数  -->
          <div @click="handleCollectClick" :class="isCollectActivate ? 'centre-left-interaction-collectKnot-activate' : 'centre-left-interaction-collectKnot-default'">
            <div class="centre-left-interaction-collect">
              <el-icon :size="30" class="iconfont icon-shoucang"></el-icon>
            </div>
            <div class="likeNum">{{article.collectNum}}</div>
          </div>
          <div class="centre-left-interaction-commentKnot">
            <div class="centre-left-interaction-comment">
              <a href="#comment">
                <el-icon :size="30" class="iconfont icon-xiaoxi"></el-icon>
              </a>
            </div>
            <div class="likeNum">{{total}}</div>
          </div>
        </div>
      </div>
      <!-- 左侧图标结束 -->

      <div class="centre-centre">
        <div class="centre-centre-articleArea">
          <div class="centre-centre-articleArea-title">{{ article.title }}</div>
          <div class="centre-centre-articleArea-source">作者：{{article.createBy}}  时间：{{article.createTime}}</div>
          <hr>
          <div class="centre-centre-articleArea-content">
            <!-- {{article.content}} -->
            <v-md-editor
              :model-value="article.content"
              mode="preview"
            ></v-md-editor>
          </div>
        </div>
        <hr>
        <div id="comment" class="centre-centre-commentArea">
          <u-comment-scroll :disable="disable" @more="more">
            <u-comment :config="config" @submit="submit" @like="like">
              <!-- 下一行决定是否出现最新/最热，对应绑定的排序函数没有补全 -->
              <!-- <u-comment-nav v-model="latest" @sorted="sorted"></u-comment-nav> -->
              <!-- <template>导航栏卡槽</template> -->
              <!-- <template #header>头部卡槽</template> -->
              <!-- <template #action="{ user }">动作卡槽{{ user.username }}</template> -->
              <!-- <template #avatar="{ id, user }">头像卡槽{{ user.avatar }}</template> -->
              <!-- <template #info>信息卡槽</template> -->
              <!-- <template #card>用户信息卡片卡槽</template> -->
              <!-- <template #func>功能区域卡槽</template> -->
            </u-comment>
          </u-comment-scroll>
        </div>
      </div>

      <div class="centre-right">
        <div class="centre-right-top">相关推荐</div>
        <div class="centre-right-bottom">
          <ol>
            <li>咖啡</li>
            <li>牛奶</li>
            <li>茶</li>
          </ol>
        </div>
        <div v-if="showReturnTop" class="centre-right-returnTop">
          <a href="#top">
            <el-icon size="30"><Top /></el-icon>
          </a>
        </div>
      </div>
    </div>
    <LoginDialog v-model="loginDialogVisible" @close-dialog="closeDialog"></LoginDialog>
    <CollectDialog v-model="collectDialogVisible" @close-Cdialog="closeCDialog($event)" :articleId="route.query.articleId"></CollectDialog>
  </div>
</template>

<script setup lang="ts">
import emoji from '@/utils/emoji'
import { reactive, ref, onMounted, onUnmounted} from 'vue'
import { UToast, Time, CommentApi, CommentSubmitApi, ConfigApi, cloneDeep, usePage, CommentReplyPageApi } from 'undraw-ui'
import {useRouter, useRoute} from 'vue-router'
import LoginDialog from './components/LoginDialog.vue';
import CollectDialog from './components/CollectDialog.vue';
import {articleApi} from '@/api/article.js'
import {historyApi} from '@/api/history.js'
import {userApi} from '@/api/user.js'
import {commentApi} from '@/api/comment.js'
import {searchEngineApi} from '@/api/searchEngine.js'
import {collectApi} from '@/api/collect.js'
import { ElMessage, ElMessageBox } from 'element-plus'
import {settingApi} from '@/api/setting.js'

//### 变量定义 ###
const router = useRouter(); //路由器
const route = useRoute(); //路由
const topVisible = ref(false);  //控制回到顶部按钮是否显示
const avatar = ref('http://8.130.118.52:9000/images/headPortrait/defaultHead.png');  //头像
const nickname = ref('游客');  //昵称
const isUpvoteActivate = ref(false); //控制点赞样式
const isCollectActivate = ref(false); //控制收藏样式

const searchQuery = ref('');  //对应搜索框中的数据
const loginDialogVisible = ref(false);  //控制登录对话是否显示
const collectDialogVisible = ref(false);  //控制收藏对话是否显示
const showReturnTop = ref(false); //控制返回顶部图标是否显示
const scrollThreshold = 600;      // 定义一个阈值，当滚动超过这个高度时显示图标
const isDarkmode = ref(false);  //是否开启夜间模式
const article = ref({
  title: "默认文章",
  content: "我只是一个因为网络请求失败而显示的默认文章嘛",
  likeNum: 999,
  collectNum: 999,
  createBy: "张三",
  createTime: "2002-4-16"
})

const history = ref({ //记录历史记录所需
  title: "",
  type: 1,
  url: "",
})

//存储搜索过的历史记录
const historys = ref<string[]>([]);

const searchRecord = ref([
  '把大象放进冰箱需要几步？',
  'Java是世界上最好的语言',
  'Python是世界上最好的语言',
  'js是世界上最好的语言',
  // 更多数据...
]);

//评论区所需变量
const config = reactive<ConfigApi>({  //一个与评论有关的配置类
  user: {} as any, // 当前用户信息
  emoji: emoji, // 表情包数据
  comments: [], // 评论数据
  relativeTime: true, // 开启人性化时间
  page: true // 开启分页
})

const disable = ref(false); // 是否禁用滚动加载评论

const pageGetCommentPara = reactive({//评论获取分页参数
  current: 1,
  size: 5,
  articleId: ""
})

let total = ref(0); //评论条数

//### 方法定义 ###
// 页面初始化方法
const pageInitialization = async () => {
  //初始化历史记录
  const result = await historyApi.obtainTheHistoricalRecordsTo5ThroughTheUserId();
  if(result.code === 200) {
    historys.value = result.data.titles;
  }

  const name =  window.localStorage.getItem('ten-seek-nickname')
  if(name)  {
    nickname.value = name;
  }
  const head = window.localStorage.getItem('ten-seek-avatar')
  if(head) {
    avatar.value = head;
  }

  const articleId = route.query.articleId as string;
  if(articleId) {
    console.log("文章id", articleId)
    pageGetCommentPara.articleId = articleId; //评论分页请求参数获取对应文章id
    const result = await articleApi.getByIdArticleNoNeed(articleId);
    console.log("看看", result);
    if(result.code == 200) {  //需要文章被正确初始化 后续的才有意义
      //赋值
      article.value = result.data;

      const setting= await settingApi.getSettingContentIsOpenByName({"name":"无痕浏览模式"});
      console.log("看看无痕设置", setting)
      if(setting.code === 200 && !setting.data) { //没有开启无痕浏览才记录历史
        //记录历史
        history.value.title = article.value.title;
        history.value.url = route.fullPath;
        const h = await historyApi.recordPersonalHistoricalRecords(history.value);
        console.log("历史记录信息：", h);
      }

      //判断当前登录用户是否为对应文章点赞
      const isLikedArticle = await articleApi.isLikedArticle({"articleId":articleId});
      console.log(isLikedArticle, "dddd")
      if(isLikedArticle.code === 200) {
        isUpvoteActivate.value = isLikedArticle.data;  //赋值以便默认显示
      }

      //判断当前登录用户是否已经收藏对应文章
      const isTheArticleFavorited = await collectApi.isTheArticleFavorited({"articleId":articleId});
      if(isTheArticleFavorited.code === 200) {
        isCollectActivate.value = isTheArticleFavorited.data;
      }

      //获取当前登录用户基本信息，用于评论区展示
      const currentUserInfo = await userApi.getTheBasicInformationOfTheCurrentUser();
      config.user = currentUserInfo.data;

      //分页获取对应评论列表数据
      const commentList = await commentApi.queryTheCommentListByPageAccordingToTheArticleId(pageGetCommentPara);
      if(commentList.code === 200) {
        total.value = commentList.data.total;
        // console.log("看看获取的评论列表数据", commentList.data.commentAndUserInfoAndReplyVOList);
        config.comments = commentList.data.commentAndUserInfoAndReplyVOList;
      }
    }
  }else {
    //显示默认
  }
}

//### 初始化方法调用
pageInitialization();

//### 处理点赞收藏样式修改事件
const handleUpvoteClick = async () => {
  // console.log("点赞被点了")
  isUpvoteActivate.value = isUpvoteActivate.value ? false : true;
  const articleId = route.query.articleId as string;
  const result = await articleApi.likeArticle({"articleId": articleId});
  if(result.code === 200) {
    article.value.likeNum = result.data.likeNum;
  }
}

//收藏按钮监听方法
const handleCollectClick = async () => {
  if(!isCollectActivate.value) { //说明是收藏操作
    collectDialogVisible.value = true;
  }else { //反之取消收藏
    ElMessageBox.confirm('你确定要取消对应文章的收藏吗？')
    .then(async () => {
      const articleId = route.query.articleId as string;
      const result = await collectApi.removeCollectionRecords({"articleId": articleId});
      if(result.code == 200) {
        isCollectActivate.value = !isCollectActivate.value;
        article.value.collectNum = result.data.collectNum;  //更新收藏数量
      }else {
        ElMessage({
          type: 'error',
          message: "取消收藏失败",
        })
      }
    })
    .catch(() => {
      
    })
  }
}

// 滚动事件处理函数
const handleScroll = () => {
  const scrollTop = window.pageYOffset || document.documentElement.scrollTop;    // 获取当前页面的滚动位置
  showReturnTop.value = scrollTop > scrollThreshold;            // 根据滚动位置更新图标的显示状态
};

//搜索选中事件
const handleSelect = (selectItem:any) => {
  console.log("让我看看你选了", selectItem) //小心这里拿到的是ref
  const selectedValue = selectItem.value.replace(/<[^>]+>/g, ''); //移除对应html标签
  searchQuery.value = selectedValue;
}

//搜索提示词
const querySearch = async (queryString:any, cb:any) => {
  let results = null;
  if(queryString === '') {
    results = historys.value.map(item => ({ value: item }));  //表示搜索框中的数据为空时，搜索提示历史数据
  }else {
    const data = await searchEngineApi.searchPrompt({suffix:queryString});
    if(data.code === 200) {
      console.log(data.data.complementList)
      const autocompleteData = data.data.complementList.map(item => ({ value: item }));
      results = autocompleteData;
    }else {
      results = searchData.value.map(item => ({ value: item }));
    }
  }

  cb(results);     // 使用回调函数返回搜索结果
};

//个人中心点击方法
function clickPersonalCenterEvent() {
  let token = window.localStorage.getItem("ten-seek-jwt")
  if(token) {
    router.push({
      name: 'collect'
    });
  }else {
    loginDialogVisible.value = true;
  }
}

//搜索按钮点击方法
const clickSearchEvent = () => {
  if(!searchQuery.value) {
    ElMessage({
      message: '搜索内容请不要为空哦！',
      type: 'warning',
    })
    return;
  }
  //获取搜索字段
  router.push({ name: 'searchResult', query: { query: searchQuery.value }});
}

//logo点击方法
function clickLogo() {
  router.push({
    name: 'home'
  })
}

//## 自定义事件方法
function closeDialog() {
	loginDialogVisible.value = false;
}
//关闭收藏弹窗
const closeCDialog = (arg:number) => {
  collectDialogVisible.value = false;
  if(arg !== -1) {
    //到此处说明子组件完成了收藏操作
    article.value.collectNum = arg;  //更新收藏数量
    isCollectActivate.value = isCollectActivate.value ? false : true;
  }
}

//### 生命周期函数 ###
// 组件挂载时添加滚动事件监听器
onMounted(() => {
  window.addEventListener('scroll', handleScroll);

  //夜间模式检查
  let darkmode = window.localStorage.getItem('tenSeekIsDarkmode');
  if(darkmode === 'true') {
    isDarkmode.value = true;
  }
});
 
// 组件卸载时移除滚动事件监听器，避免内存泄漏
onUnmounted(() => {
  window.removeEventListener('scroll', handleScroll);
});


//### 与评论区有关的逻辑 ###
// 评论提交事件
const submit = async ({ content, parentId, finish }: CommentSubmitApi) => {
  console.log("查看提交评论信息：", content, parentId, finish)
  const articleId = route.query.articleId as string;  //从路由参数中获取对应文章id
  const result = await commentApi.addComment({content, parentId, articleId});
  if(result.code === 200) {
    finish(result.data.commentAndUserInfoAndReplyVO);
    if(parentId === null) {
      //先前端处理，后续通过异步请求获取新的一级评论总条数
      total.value = Number(total.value) + 1;
    }
    UToast({ message: '评论成功!', type: 'info' });
  }
}

// 点赞按钮事件
const like = async (id: string, finish: () => void) => {
  console.log('点赞id查看: ' + id)
  const result = await commentApi.liked({"commentId": id});
  if(result.code === 200) {
    finish()
  }
}

// 模拟接口请求加载更多评论
const more = async () => {
  // console.log(disable.value)
  if (pageGetCommentPara.current <= Math.ceil(total.value / pageGetCommentPara.size)) {
    pageGetCommentPara.current = pageGetCommentPara.current + 1;  //查询下一页
    const commentList = await commentApi.queryTheCommentListByPageAccordingToTheArticleId(pageGetCommentPara);
    if(commentList.code === 200) {
      // console.log(commentList.data.commentAndUserInfoAndReplyVOList);
      config.comments.push(...commentList.data.commentAndUserInfoAndReplyVOList); //注意多个参数需要 ...符号
    }
  } else {
    disable.value = true
  }
}

//排序
// const latest = ref(true)
// const sorted = (latest: boolean, finish: () => void) => {
//   //是最新还是最热
//   console.log(latest)
// }
</script>


<style scoped lang="scss">
.container {
  // background: antiquewhite;
  height: 100%;
  display: flex;
  flex-direction: column;
  background: var(--base-color);
  color: var(--text-color);

  .top {
    // background: cyan;
    width: 100%;
    flex: 1;
    margin-top: 5px;

    display: flex;
    justify-content: space-between; /* 使子项在主轴上两端分布 */
    align-items: center; /* 垂直居中 */

    .top-left {
      // background: beige;
      width: 60%;

      display: flex;
      .top-left-logo {
        margin-left: 25px;
        margin-right: 25px;
        display: flex;
        flex: 2;

        img {
          align-items: center; /* 垂直居中 */
          width: 100%;
        }
      }

      .top-left-search{
        margin: auto;
        height: 42px;
        flex: 8;

        text-align: center;
        display: flex;
        align-items: center;

        .top-left-search-input {
          flex: 0.92;
          height: 100%;

          /* 深度样式控制，通过f12工具找到对应的名字进行样式设置 */
          ::v-deep .el-input__wrapper {
            border-top-left-radius: 10px; 
            border-bottom-left-radius: 10px; 
            border-top-right-radius: 0px; 
            border-bottom-right-radius: 0px;
            height: 42px; /* 要和对应centre-search高度一致 */
            background: var(--base-color);
          }

          /* 输入框内文字的颜色 */
          ::v-deep .el-input__inner {
            color: var(--text-color);
          }
        }

        .top-left-search-icon {
          background: #409EFF;
          flex: 0.08;
          height: 100%;
          border-top-left-radius: 0px;
          border-bottom-left-radius: 0px;
          border-top-right-radius: 10px;
          border-bottom-right-radius: 10px;
        }
      }
    }

    .top-right {
      // background: blueviolet;
      .top-right-person {
        margin-right: 20px;
        display: flex;
        align-items: center;
        height: 100%;

        img {
          border-radius: 50%;
          width: 50px;       /* 固定宽度 */
          height: 50px;      /* 固定高度，与宽度相同 */
          object-fit: cover; /* 保证图片比例不变形 */
          margin-right: 10px;
          display: block;    /* 避免行内元素的间隙问题 */
        }

        .nickname {
        }
      }
    }
  }

  .centre {
    // background: bisque;
    flex: 9;
    margin-top: 30px;
    display: flex;
    background: var(--base-color);
    color: var(--text-color);

    .centre-left {
      // background: aqua;
      flex: 1;

      display: flex;
      flex-direction: column;
      align-items: center; /* 复轴居中 */
      margin-top: 150px;

      .centre-left-interaction {
        position: sticky;
        top: 150px;

        /* 点赞默认样式 */
        .centre-left-interaction-upvoteKnot-default {
          display: flex;
          flex-direction: column;
          align-items: center;

          .centre-left-interaction-upvote {
            // background: hotpink;
            margin-top: 20px;
            border-radius: 50%;
            padding: 8px;
            border-style: solid;
            border-width: 1px;
          }

          .likeNum {
            font-weight: bold;
          }
        }

        /* 点赞激活样式 */
        .centre-left-interaction-upvoteKnot-activate {
          display: flex;
          flex-direction: column;
          align-items: center;
          color: #409EFF;

          .centre-left-interaction-upvote {
            // background: hotpink;
            margin-top: 20px;
            border-radius: 50%;
            padding: 8px;
            border-style: solid;
            border-width: 1px;
          }

          .likeNum {
            font-weight: bold;
          }
        }

        /* 收藏默认样式 */
        .centre-left-interaction-collectKnot-default {
          display: flex;
          flex-direction: column;
          align-items: center;

          .centre-left-interaction-collect {
            // background: indianred;
            margin-top: 20px;
            border-radius: 50%;
            padding: 8px;
            border-style: solid;
            border-width: 1px;
          }

          .likeNum {
            font-weight: bold;
          }

        }

        /* 收藏激活样式 */
        .centre-left-interaction-collectKnot-activate {
          display: flex;
          flex-direction: column;
          align-items: center;
          color: #409EFF;

          .centre-left-interaction-collect {
            // background: indianred;
            margin-top: 20px;
            border-radius: 50%;
            padding: 8px;
            border-style: solid;
            border-width: 1px;
          }

          .likeNum {
            font-weight: bold;
          }

        }

        .centre-left-interaction-commentKnot {
          display: flex;
          flex-direction: column;
          align-items: center;

          .centre-left-interaction-comment {
            // background: gold;
            margin-top: 20px;
            border-radius: 50%;
            padding: 8px;
            border-style: solid;
            border-width: 1px;

            a {
              color: var(--text-color);
            }
          }

          .likeNum {
            font-weight: bold;
          }
        }
      }
    }

    .centre-centre {
      // background: red;
      flex: 5;

      display: flex;
      flex-direction: column;
      box-shadow: 0 4px 8px 0 var(--border-shadow-color), 0 6px 20px 0 var(--border-shadow-color);
      border-radius: 9px;

      .centre-centre-articleArea {
        // background: green;
        flex: 7;
        padding: 15px;

        .centre-centre-articleArea-title {
          font-size: 30px;
          font-weight: 900;
        }

        .centre-centre-articleArea-source {
          margin-top: 20px;
        }

        hr {
          margin-bottom: 20px;
        }

        .centre-centre-articleArea-content {
          font-family: Arial, Helvetica, sans-serif;
          font-size: 18px;
          line-height: 1.7;
          text-indent: 36px;

          .v-md-editor{
            background: var(--base-color);
          }

          .v-md-editor :deep(.v-md-pre-wrapper) {
            text-indent: 0px;
          }
        }
      }

      .centre-centre-commentArea {
        // background: hotpink;
        flex: 3;

        /* 评论区整体 */
        ::v-deep .u-comment {
          background: var(--base-color);
          color: var(--text-color);
        }

        /* 评论区输入框 */
        ::v-deep .rich-input {
          background: var(--base-color);
          color: var(--text-color);
        }

        /* 评论区昵称 */
        ::v-deep .name {
          color: var(--text-color);
        }

        /* 评论区回复区域 */
        ::v-deep .reply-box {
          background: var(--base-color);
          color: var(--text-color);
        }

        /* 评论区最新最热位置 */
        ::v-deep .nav__sort {
          background: var(--base-color);
        }
      }
    }

    .centre-right {
      // background: rebeccapurple;
      flex: 4;
      margin: 0px 30px;
      box-shadow: 0 4px 8px 0 var(--border-shadow-color), 0 6px 20px 0 var(--border-shadow-color);
      border-radius: 9px;
      padding: 10px;

      .centre-right-top {
        // background: greenyellow;
        font-size: 20px;
        font-weight: normal;
      }

      .centre-right-bottom {
        // background: honeydew;
        
        ol{
          li {
            font-size: 18px;
          }
        }
      }

      .centre-right-returnTop {
        position: fixed;
        right: 50px;
        bottom: 40px;

        a {
          color: var(--text-color);
        }
      }
    }
  }
}
</style>